package com.jacobson.core.widget

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.widget.Toast

/**
 * ================================================
 *
 *  @author Wucz on 2018-10-29 16:58
 * ================================================
 */

object ToastUtil {
    private var toast: Toast? = null
    private val handler = Handler(Looper.getMainLooper())

    @SuppressLint("ShowToast")
    fun toast(context: Context, msg: String, duration: Int = Toast.LENGTH_SHORT) {
        if (toast == null) {
            val appContext = context.applicationContext ?: context
            toast = Toast.makeText(appContext, msg, duration)
        }
        toast?.run {
            cancel()
            setGravity(Gravity.CENTER, 0, 0)
            setDuration(duration)
            setText(msg)
            handler.postDelayed({
                show()
            }, 100)
        }
    }

    @SuppressLint("ShowToast")
    fun toast(context: Context, msgId: Int, duration: Int = Toast.LENGTH_SHORT) {
        if (toast == null) {
            val appContext = context.applicationContext ?: context
            toast = Toast.makeText(appContext, msgId, duration)
        }
        toast?.run {
            cancel()
            setGravity(Gravity.CENTER, 0, 0)
            setDuration(duration)
            setText(msgId)
            handler.postDelayed({
                show()
            }, 100)
        }
    }
}